package net.minhdiep.androiddialoglistener;

import android.app.Activity;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.*;
import android.widget.*;

import java.io.IOException;


/*
 * User: Minh Diep
 * Date: 6/7/13
 * Time: 10:49 AM
 */

public class TextureViewActivity extends Activity {

    private Camera mCamera;
    private TextureView mTextureView;
    private SeekBar alphaSeekBar;
    private ImageView photoImageView;


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_texture_view);
        mTextureView = (TextureView) findViewById(R.id.camera_view);
        alphaSeekBar = (SeekBar) findViewById(R.id.alpha_seek_bar);
        Button captureBtn = (Button) findViewById(R.id.capture_btn);
        photoImageView = (ImageView) findViewById(R.id.photo_imageview);
        alphaSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                mTextureView.setAlpha((float) progress/100);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        captureBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                photoImageView.setImageBitmap(mTextureView.getBitmap());

            }
        });
        mTextureView.setSurfaceTextureListener(new MySurfaceTextureListener());
    }

    private class MySurfaceTextureListener implements TextureView.SurfaceTextureListener {
        @Override
        public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
            mCamera = Camera.open();
            try {
                mCamera.setPreviewTexture(surface);
            } catch (IOException t) {
            }

            mCamera.startPreview();
            mTextureView.setRotation(90);
            mTextureView.setAlpha(0.5f);
        }

        @Override
        public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {

        }

        @Override
        public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
            mCamera.stopPreview();
            mCamera.release();
            return true;
        }

        @Override
        public void onSurfaceTextureUpdated(SurfaceTexture surface) {

        }
    }
}